package tehUtils;

import java.util.Set;
import java.util.HashSet;

import net.minecraft.src.AxisAlignedBB;
import net.minecraft.src.ModLoader;
import net.minecraft.src.World;

public class BlockSearch {
	
	// bounds
	protected int maxX;
	protected int minX;
	protected int maxY;
	protected int minY;
	protected int maxZ;
	protected int minZ;
	
	// block filter info
	protected int blockID = -1;
	protected int metadata = -1;
	
	protected World worldObj;
	
	public BlockSearch(AxisAlignedBB boundingBox) {
		convertBoundingBox(boundingBox);
		worldObj = ModLoader.getMinecraftInstance().theWorld;
	}
	
	public BlockSearch(AxisAlignedBB boundingBox, int blockID) {
		convertBoundingBox(boundingBox);
		this.blockID = blockID;
		worldObj = ModLoader.getMinecraftInstance().theWorld;
	}
	
	public BlockSearch(AxisAlignedBB boundingBox, int blockID, int metadata) {
		convertBoundingBox(boundingBox);
		this.blockID = blockID;
		this.metadata = metadata;
		worldObj = ModLoader.getMinecraftInstance().theWorld;
	}
	
	private void convertBoundingBox(AxisAlignedBB boundingBox) {
		maxX = (int)Math.ceil(Math.max(boundingBox.maxX, boundingBox.minX));
		minX = (int)Math.floor(Math.min(boundingBox.maxX, boundingBox.minX));
		
		maxY = (int)Math.ceil(Math.max(boundingBox.maxY, boundingBox.minY));
		minY = (int)Math.floor(Math.min(boundingBox.maxY, boundingBox.minY));
		
		maxZ = (int)Math.ceil(Math.max(boundingBox.maxZ, boundingBox.minZ));
		minZ = (int)Math.floor(Math.min(boundingBox.maxZ, boundingBox.minZ));

	}
	
	public Set search() {
		Set output = new HashSet();
		
		for (int x = minX; x <= maxX; x++) {
			for (int y = minY; y <= maxY; y++) {
				for (int z = minZ; z <= maxZ; z++) {
					if ((worldObj.getBlockId(x, y, z) == blockID || blockID == -1)
					&& (worldObj.getBlockMetadata(x, y, z) == metadata || metadata == -1))
						output.add(new BlockInstance(x, y, z));
				}
			}
		}
		
		return output;
	}

}
